package com.yunxin.server;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.hutool.core.text.CharPool;
import cn.hutool.crypto.SecureUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;

public class WordUtil {
    /**
     * 导出word
     * <p>第一步生成替换后的word文件，只支持docx</p>
     * <p>第二步下载生成的文件</p>
     * <p>第三步删除生成的临时文件</p>
     * 模版变量中变量格式：{{foo}}
     *
     * @param templatePath word模板地址
     * @param params       替换的参数
     */
    public static void exportWord(String templatePath, Map<String, Object> params) {

        final  String bucketName = "upload-file-pro-dev";
        final String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
        final String accessKeyId = "LTAI5tLtkZwur1L3as3n3cq6";
        final String accessKeySecret = "uUxuAiMiRcds72Il9EIMPwBvYka0w1";
        final String frontDomain = "front-dev.yhshuke.com";
        //https://download-file-pro-dev.oss-cn-shenzhen.aliyuncs.com/download/template/%E5%8F%91%E7%A5%A8%E6%A8%A1%E7%89%88.docx
        String URL = "https://download-file-pro-dev.oss-cn-shenzhen.aliyuncs.com/download/template/商户发票.docx";
        //https://download-file-pro-dev.oss-cn-shenzhen.aliyuncs.com/download/template/商户分析.xlsx
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(URL, params);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            doc.write(byteArrayOutputStream);

            // 把文件写入字节输出流
            doc.write(byteArrayOutputStream);
            // 输出流转成输入流
            InputStream inputStreams = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            String md5 = SecureUtil.md5("1231231312");
            String fileName = "test" + CharPool.SLASH + md5 + CharPool.DOT + "docx";
            ossClient.putObject(bucketName, fileName, inputStreams);
            ossClient.shutdown();
            doc.close();
            String fileUrl = frontDomain + CharPool.SLASH + fileName;
            System.out.println(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}